//
//  QYEmotionDetailVC.swift
//  QingYuJSQ
//
//  Created by 李东 on 2024/4/5.
//

import UIKit
import UniformTypeIdentifiers

class QYEmotionDetailVC: QYBaseVC {

    @IBOutlet weak var closeBtn_top: NSLayoutConstraint!
    @IBOutlet weak var weekLabel: UILabel!
    @IBOutlet weak var dayLabel: UILabel!
    @IBOutlet weak var emoImgView: UIImageView!
    @IBOutlet weak var emoNameLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var contentTV: UITextView!
    @IBOutlet weak var picImgView: UIImageView!
    
    @IBOutlet weak var contentTV_top: NSLayoutConstraint!
    
    
    var model: QYDataModel!
    var emotion = ""
    var selectDate: Date!
    
    init(model: QYDataModel = QYDataModel(), emotion: String = "", selectDate: Date!) {
        super.init(nibName: nil, bundle: nil)
        self.model = model
        self.emotion = emotion
        self.selectDate = selectDate
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        hideNavgaitionBar()
        closeBtn_top.constant = CGFloat.topPadding
        NotificationCenter.default.addObserver(self, selector: #selector(keyboradWillShow(sender:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        view.addSubview(toolBar)
        contentTV.becomeFirstResponder()
        

        if model.ids != 0 {
            contentTV.text = model.content
            emoImgView.image = UIImage(named: model.emotion)
            emoNameLabel.text = model.emotion
            picImgView.image = UIImage(contentsOfFile: CompressedHelper.shared.getFilePath(fileName: model.fileName))
            if model.time.isEmpty {
                timeLabel.text = ""
                contentTV_top.constant = -5
            }else{
                timeLabel.text = model.time
                contentTV_top.constant = 10
            }
            emotion = model.emotion
            weekLabel.text = model.week
            dayLabel.text = model.date
        }else {
            emoImgView.image = UIImage(named: emotion)
            emoNameLabel.text = emotion
            contentTV_top.constant = -5
            let ss = df.string(from: selectDate).components(separatedBy: " ")
            weekLabel.text = ss[0]
            dayLabel.text = ss[1]
        }
        emoImgView.isUserInteractionEnabled = true
        emoImgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectEmotion)))
      
        NotificationCenter.default.post(name: .HideVCdNoti, object: nil)

    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    lazy var df: DateFormatter = {
        let temp = DateFormatter()
        temp.locale = Locale(identifier: "en_US")
        temp.dateFormat = "EEEE M.d"
        return temp
    }()
    
    
    lazy var df1: DateFormatter = {
        let temp = DateFormatter()
        temp.locale = Locale(identifier: "zh_CN")
        // 设置日期格式，yyyy表示年份，MMMM表示中文大写的月份
        temp.dateFormat = "yyyy年M月"
        return temp
    }()
    
    lazy var df2: DateFormatter = {
        let temp = DateFormatter()
        temp.locale = Locale(identifier: "zh_CN")
        temp.dateFormat = "HH:mm"
        return temp
    }()
    
    lazy var df3: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyyMMdd"
        return temp
    }()
    

    lazy var toolBar: QYToolBar = {
        let temp = QYToolBar(frame: CGRect(x: 0, y: CGFloat.screenHeight, width: CGFloat.screenWidth, height: 45))
        temp.clickCallBack = {[weak self] isPic in
            guard let self = self else {
                return
            }
            if isPic {
                self.showPicPicker()
            }else{
                self.addTime()
            }
        }
        return temp
    }()
    
    @IBAction func closeHandle(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBAction func finishHandle(_ sender: Any) {
        if model.ids == 0 {
            model.ids = Int(TimeInterval(Date().timeIntervalSince1970))
            model.yearAndMonth = df1.string(from: selectDate)
            let str = df3.string(from: selectDate)
            let tempDate = df3.date(from: str) ?? Date()
            model.ts = Int(TimeInterval(tempDate.timeIntervalSince1970))
            model.date = dayLabel.text ?? ""
            model.week = weekLabel.text ?? ""
        }
       
        model.content = contentTV.text
        model.emotion = emotion
        model.time = timeLabel.text ?? ""
        model.height = Int(countCellHeight()) + 1
        QYDataHelper.shared.addData(model: model)
        NotificationCenter.default.post(name: .DataDidChangedNoti, object: nil)
        showHUDTextOnly("已保存") {[weak self] in
            guard let self = self else {
                return
            }
            self.dismiss(animated: true)
        }
    }
    
    //计算cell高度存起来，列表展示使用
    func countCellHeight() -> CGFloat{
        var cellHeight: CGFloat = 195
        if !model.time.isEmpty {//时间部分的高度
            cellHeight += 32
        }
        if !model.content.isEmpty {
            cellHeight += 15
            let contentHeight = model.content.getHeight(font: UIFont.systemFont(ofSize: 16), width: CGFloat.screenWidth - 80)
            cellHeight += contentHeight
        }
        cellHeight += 45
        if !model.fileName.isEmpty {
            cellHeight += (CGFloat.screenWidth-80+20)
        }
        return cellHeight
    }
    
    @objc func selectEmotion() {
        let vc = QYSelectEmotionVC(isEdit: true)
        vc.modalPresentationStyle = .fullScreen
        vc.selectCallBack = {[weak self] newEmotion in
            guard let self = self else { return }
            self.emotion = newEmotion
            self.model.emotion = newEmotion
            self.emoImgView.image = UIImage(named: newEmotion)
            self.emoNameLabel.text = newEmotion
        }
        present(vc, animated: true)
    }
    
    func showPicPicker()  {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let action1 = UIAlertAction(title: "相机", style: .default) { _ in
            self.selectPhoto(type: .camera)
        }
        let action2 = UIAlertAction(title: "相册", style: .default) { _ in
            self.selectPhoto(type: .photoLibrary)
        }
        let action3 = UIAlertAction(title: "取消", style: .cancel)
        alert.addAction(action1)
        alert.addAction(action2)
        alert.addAction(action3)
        present(alert, animated: true)
        
    }
    
    func selectPhoto(type: UIImagePickerController.SourceType)  {
        RXPermissionUtils.albumAndCamera(type: type) {[weak self] in
            guard let self = self else {
                return
            }
            let picker = UIImagePickerController()
            picker.sourceType = type
            picker.delegate = self
            picker.allowsEditing = false
            if #available(iOS 14.0, *) {
                picker.mediaTypes = [UTType.image.identifier]
            } else {
                // Fallback on earlier versions
                picker.mediaTypes = ["images"]
            }
            self.present(picker, animated: true)
        }
   
    }
    
    func addTime() {
        timeLabel.text = "[\(df2.string(from: Date()))]"
        contentTV_top.constant = 10
    }
    

    @objc func keyboradWillShow(sender: Notification) {
        if let keyboardSize = (sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            // 键盘的尺寸
            let keyboardHeight = keyboardSize.height
            UIView.animate(withDuration: 0.15) {
                self.toolBar.y = CGFloat.screenHeight - 45 - keyboardHeight
            }
        }
    }
    
    @objc func keyboardWillHide(sender: Notification) {
        UIView.animate(withDuration: 0.15) {
            self.toolBar.y = CGFloat.screenHeight
        }
    }
    
}

extension QYEmotionDetailVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        guard let img = info[.originalImage] as? UIImage else {
            return
        }
        view.endEditing(true)
        let fileName = "\(Date().timeIntervalSince1970).jpg"
        CompressedHelper.shared.writeData(data: img.jpegData(compressionQuality: 0.5)!, fileName: fileName)
        picImgView.image = img
        model.fileName = fileName
        
    }
    
    
}
